package org.lixue.game.server.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.lixue.game.server.config.BaseConfig;
import org.lixue.game.server.handler.socket.MessageDecoder;
import org.lixue.game.server.handler.socket.MessageEncoder;

@Slf4j
public class MockClient {
    public static void main(String[] args) {
        String host = "localhost";
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch)
                        throws Exception {
                    // in
                    ch.pipeline().addLast(new MessageDecoder());
                    // out
                    ch.pipeline().addLast(new MessageEncoder());

                    // business handler
                    ch.pipeline().addLast(new MessageClientHandler());
                }
            });

            ChannelFuture f = b.connect(host, BaseConfig.port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("error->" + e);
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
